package com.bear.hospital.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bear.hospital.utils.JwtContext;
import com.bear.hospital.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();

        // 获取请求头中的令牌
        String token = request.getHeader("token");

        try {
            DecodedJWT verify = JwtUtil.verify(token); // 验证令牌
            log.info(JSON.toJSONString(verify.getPayload()));
            log.info(JSON.toJSONString(verify.getPayload()));
            JwtContext.setJwtInfo(verify); // 将解析的信息存入线程上下文
            String payload = new String(Base64.getUrlDecoder().decode(verify.getPayload()));
            log.info("JWT Payload (as String): {}", payload);
            // 将Payload转换为Map对象
            Map<String, Object> payloadAsMap = JSON.parseObject(payload, new HashMap<String, Object>().getClass());
            JwtContext.setUserName((String) payloadAsMap.get("userName"));
            return true;
        } catch (SignatureVerificationException e) {
            log.error("无效签名", e);
            map.put("msg", "无效签名！");
        } catch (TokenExpiredException e) {
            log.error("token过期", e);
            map.put("msg", "token过期！");
        } catch (AlgorithmMismatchException e) {
            log.error("token算法不一致", e);
            map.put("msg", "token算法不一致！");
        } catch (Exception e) {
            log.error("token无效", e);
            map.put("msg", "token无效！");
        }

        map.put("state", false);
        String json = JSON.toJSONString(map); // 使用FastJSON统一处理JSON
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        return false;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal变量
        JwtContext.clear();
    }
}